package org.example.domain.strategy.service.armory;


import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import org.example.domain.strategy.model.entity.StrategyEntity;
import org.example.domain.strategy.model.entity.StrategyRuleEntity;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.types.common.Constants;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * 策略装配库(兵工厂)，负责初始化策略计算
 */
@Slf4j
@Service
public class StrategyArmoryDispath implements IStrategyArmory,IStrategyDispath{

    @Resource
    private IStrategyRepository repository;

    @Override
    public boolean assembleLotteryStrategyByActivityId(Long activityId){
        Long strategyId = repository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);
    }

    /**
     * 装配抽奖策略
     * @param strategyId
     * @return
     */
    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {

        //1.查询策略配置，并装配
        List<StrategyAwardEntity> strategyAwardEntities =  repository.queryStrategyAwardList(strategyId);
        assembleLotteryStrategy(String.valueOf(strategyId),strategyAwardEntities);

        //2.缓存奖品库存【用于decr扣减库存使用】
        for(StrategyAwardEntity strategyAward : strategyAwardEntities){
            Integer awardId = strategyAward.getAwardId();
            Integer awardCount = strategyAward.getAwardCount();
            cacheStrategyAwardCount(strategyId,awardId,awardCount);
        }

        //3.权重策略配置-适用于rule_weight权重规则配置
        //3.1将策略实体中的rule_weight查询出来
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String ruleWeight = strategyEntity.getRuleWeight();
        if(ruleWeight == null) return true;
        //3.2根据rule_weight和strategyId将具体的权重内容从策略规则实体中查询出来
        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId,ruleWeight);
        if(strategyRuleEntity == null){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        //3.3将那些不在权重范围内的策略奖品去掉，然后装配
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        Set<String> keys = ruleWeightValueMap.keySet();
        for(String key : keys){
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key),strategyAwardEntitiesClone);
        }
        return true;

    }



    /**
     * 装配抽奖策略（实际的）
     * @param key
     * @param strategyAwardEntities
     */
    public void assembleLotteryStrategy(String key,List<StrategyAwardEntity> strategyAwardEntities){
        //1.获取最小概率值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        //2.获取概率值总和
        BigDecimal totalAwradRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        //3.获得概率范围
        BigDecimal rateRange = totalAwradRate.divide(minAwardRate, 0, RoundingMode.CEILING);

        //4.生成策略奖品概率查找表【这里指需要在list集合中，存放对应的奖品占位即可，占位越多等于概率越高】
        List<Integer>  strategyAwardSearchRateTable = new ArrayList<>(rateRange.intValue());
        for(StrategyAwardEntity strategyAward : strategyAwardEntities){
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            //计算出每个概率值需要存放到查找表的数量，循环填充
            for(int i = 0;i < awardRate.multiply(rateRange).setScale(0,RoundingMode.CEILING).intValue();i++){
                strategyAwardSearchRateTable.add(awardId);
            }
        }

        //5.对存储的奖品进行乱序操作
        Collections.shuffle(strategyAwardSearchRateTable);

        //6.生成出Map集合，key值，对应的就是后续的概率值，通过概率来获得对应的奖品ID
        Map<Integer,Integer>  shufflestrategyAwardSearchRateTable = new LinkedHashMap();
        for(int i=0;i<strategyAwardSearchRateTable.size();i++){
            shufflestrategyAwardSearchRateTable.put(i,strategyAwardSearchRateTable.get(i));
        }

        //7.存放到Redis
        repository.storeStrategyAwardSearchRateTable(key,shufflestrategyAwardSearchRateTable.size(),shufflestrategyAwardSearchRateTable);

    }


    /**
     * 获取随机奖品的id
     * @param strategyId
     * @return
     */
    @Override
    public Integer getRandomAwardId(Long strategyId) {

        //获取策略对应的概率范围，用于指定随机值的生成范围
        int rateRange = repository.getRateRange(strategyId);
        //通过生成的随机值，获取概率值奖品查找表的结果
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId),new SecureRandom().nextInt(rateRange));
    }

    /**
     * 获取在权重范围内的随机奖品的id
     * @param strategyId
     * @param ruleWeightValue
     * @return
     */
    @Override
    public Integer getRandomAwardId(Long strategyId,String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        //获取策略对应的概率范围，用于指定随机值的生成范围
        int rateRange = repository.getRateRange(key);
        //通过生成的随机值，获取概率值奖品查找表的结果
        return repository.getStrategyAwardAssemble(key,new SecureRandom().nextInt(rateRange));
    }

    /**
     * 缓存奖品库存到redis
     * @param strategyId
     * @param awardId
     * @param awardCount
     */
    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {

        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId +Constants.UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey,awardCount);

    }


    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId, Date endDateTime) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId +Constants.UNDERLINE + awardId;
        return repository.subtractionAwardStock(cacheKey,endDateTime);
    }
}
